package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.PreparedStatement;

@WebServlet("/addart")
public class AddArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      String msg="未知错误";
      int data=0;
      //验证用户登录状态
        UserInfo userInfo= SessionUtils.getLoginUser(req);
        if (userInfo != null) {
            //1.得到并验证参数
            String title=req.getParameter("title");
            String context=req.getParameter("context");
            if(!StrUtil.isBlank(title) && !StrUtil.isBlank(context)){
                //2.向数据库中添加数据
                //2.1 得到当前用户的uid
                    Connection connection= DBUtils.getConnection();
                    String sql=" insert into article(title,context,uid) values(?,?,?)";
                    PreparedStatement statement = connection.prepareStatement(sql);
                    statement.setString(1,title);
                    statement.setString(2,context);
                    statement.setInt(3,userInfo.getUid());
                    data=statement.executeUpdate();
                    msg="";
                    DBUtils.close(null,statement,connection);

            }else{
                msg="参数错误";
            }
        }else{
            msg="请先登录";
        }


        //3.将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
